from django.shortcuts import render
from rest_framework.views import APIView
from .serializer import *
from rest_framework.response import Response
from django.core.paginator import Paginator
class ActorView(APIView):
    def post(self,request):
        name=request.POST.get("name")
        if models.Actor.objects.filter(name=name):
            return Response({"msg":"已存在","code":1001})
        obj=ActorUnserializers(data=request.data)
        if obj.is_valid():
            flay=obj.save()
            if flay:
                return Response({"msg":"成功","code":1000})
            return Response({"msg":"失败","code":1002})
        print(obj.errors)
        return Response({"msg":"参数错误","code":1003})
    def get(self,request):
        actorlists=models.Actor.objects.all()
        obj=Actorserializers(actorlists,many=True)
        return Response(obj.data)

class MoviesView(APIView):
    def post(self,request):
        movies_name=request.POST.get("movies_name")
        add_time=request.POST.get("add_time")
        img=request.FILES.get("img")
        actor=request.POST.get("actor")
        lists=[i for i in actor if i != ',']
        if models.Movies.objects.filter(movies_name=movies_name):
            return Response({"msg":"已存在","code":1001})
        data={
            'movies_name':movies_name,
            'add_time':add_time,
            'img':img,
            'actor':lists
        }
        obj=MoviesUnserializers(data=data)
        if obj.is_valid():
            flay=obj.save()
            if flay:
                return Response({"msg":"成功","code":1000})
            return Response({"msg":"失败","code":1002})
        print(obj.errors)
        return Response({"msg":"参数错误","code":1003})

    def get(self,request):
        pid=request.GET.get('pid')
        lists=models.Movies.objects.all()
        paginotor=Paginator(lists,5)
        pages=paginotor.page(pid)
        movie_serializer=MoviesUnserializers(pages,many=True)
        return Response({'page_sum':paginotor.num_pages,'page_list':[i for i in paginotor.page_range],'data':movie_serializer.data})



class Showmovies(APIView):
    def get(self,request):
        cid=request.GET.get('cid')
        movie_list=models.Movies.objects.get(pk=cid)
        obj=MoviesUnserializers(movie_list)
        return Response(obj.data)